<template>
    <div>
      <div id="map"></div>
      <div id="popup" class="ol-popup">
        <a href="#" id="popup-closer" class="ol-popup-closer"></a>
        <div id="popup-content">
          <ul id="message">

          </ul>
        </div>
      </div>
      <!-- <form class="form-inline">
          <label>Geometry type &nbsp;</label>
          <select name="" id="type">
              <option value="Point">Point</option>
              <option value="LineString">LineString</option>
              <option value="Polygon">Polygon</option>
              <option value="Circle">Circle</option>
              <option value="None">None</option>
          </select>
      </form> -->
      <div class="flexSb">
        <div class="flexStart">
          <label>当前坐标：</label>
          <div id="mouse-position"></div>
        </div>
        <div><el-button id="reDraw" class="btnDefault mapBtn">重画</el-button></div>
      </div>
    </div>
</template>

<script>
import 'ol/ol.css';
import ol from 'ol';
import Map from 'ol/Map';
import {register} from 'ol/proj/proj4';
import proj4 from 'proj4';
// import tilegrid from 'ol/tilegrid';
// import Layer from 'ol/layer/Layer';
import View from 'ol/View';
import proj from 'ol/proj';
import {Draw, Modify, Snap} from 'ol/interaction';
import {toStringHDMS, toStringXY, createStringXY} from 'ol/coordinate'
import Overlay from 'ol/Overlay'
import { defaults } from "ol/control";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import {get as getproj} from 'ol/proj';
import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
import {defaults as defaultControls} from 'ol/control';
import MousePosition from 'ol/control/MousePosition';
import TileLayer from 'ol/layer/Tile';
import TileArcGISRest from 'ol/source/TileArcGISRest';
import TileGrid from 'ol/tilegrid/TileGrid';
import Control from 'ol/control/Control';
import OSM from 'ol/source/OSM';
import baseUrl from "../../../public/config.json";
  export default {
    props:['mapSelectType'],
    data() {
      return {
        map: {},
        jwdMapArr:[],
      };
    },
    computed: {},
    mounted() {

        var container = document.getElementById('popup');
        var content = document.getElementById('popup-content');
        var closer = document.getElementById('popup-closer');
        //创建一个叠加层，将弹出式窗口定位到地图。
        var overlay = new Overlay(({
            element: container,
            autoPan: true,
            autoPanAnimation:{
                duration:250
            }
        }));

        //点击关闭按钮  关闭弹窗
        // closer.onclick = function () {
        //     overlay.setPosition(undefined);
        //     closer.blur();
        //     return false;
        // }


        const extent = [114.02, 28.53, 125.13, 38.08];
        proj4.defs("EPSG:4490", "+proj=longlat +=GRS80 +no_defs");
        register(proj4);
        var proj4490 = getproj("EPSG:4490");
        proj4490.setExtent(extent);
        // var projection = new getproj("EPSG:4490");
        var mousePositionControl = new MousePosition({
          coordinateFormat: createStringXY(4),
          projection: proj4490,
          // comment the following two lines to have the mouse position
          // be placed within the map.
          className: 'custom-mouse-position',
          target: document.getElementById('mouse-position'),
          undefinedHTML: '&nbsp;'
        });
        const tileGrid = new TileGrid({
          // extent:[116.33666010141599,30.710077073867467,122.14355555518478,35.177583267870595],
          extent: [-180, -89.99999933432929, 180.00000000976314, 90],
          origin: [-180, 90],
          resolutions: [
            1.406250026231578,
            0.703125013115789,
            0.3515625065578945,
            0.17578125327894775,
            0.08789062663947399,
            0.043945313319736994,
            0.021972656659868472,
            0.010986328329934226,
            0.005493164164967124,
            0.0027465820824835504,
            0.0013732910412417797,
            6.866455206208899e-4,
            3.433227603104438e-4,
            1.716613801552224e-4,
            8.583069007761132e-5,
            4.291534503880566e-5,
            2.1457672519402802e-5,
            1.0728836259701401e-5,
            5.364418129850712e-6,
            2.682209064925356e-6,
            1.341104532462678e-6
          ],
          tileSize: 256
        });
        var source= new TileArcGISRest({
          url: baseUrl.baseMap,
          tileGrid: tileGrid,
          projection: proj4490,
        });
        var sourceDraw = new VectorSource({
          wrapX: false,
        });
        var raster = new VectorLayer({
          id: "drawLayer",
          source: sourceDraw,
          projection: proj4490,
          style: new Style({
            fill: new Fill({
              color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new Stroke({
              color: '#ffcc33',
              width: 2
            }),
            image: new CircleStyle({
              radius: 7,
              fill: new Fill({
                color: '#ffcc33'
              })
            })
          })
        });
        var vector = new TileLayer({
            id: "mapLayer",
            source: source
        });
        var map = new Map({
          controls: defaultControls().extend([mousePositionControl]),
          overlays: [overlay],
          layers: [
            vector,
            raster
          ],
          target: 'map',
          view: new View({
              center: [119.13564672662321, 32.24850585937505],
              zoom: 7,
              minZoom: 2,
              maxZoom: 13,
              origin: [117.58, 33.3],
              projection: proj4490
          }),
    //       controls:defaults({
    //           attributionOptions:{
    //           collapsible:false
    //       }
    // })
        });
        this.map = map;
        var modify = new Modify({source: sourceDraw});
        map.addInteraction(modify);
        let layers = map.getLayers().array_;
        // var typeSelect = document.getElementById('type');

        var draw,snap;
        var _this = this;

        function addInteraction() {
            if(_this.mapSelectType !== 'None'){
                draw = new Draw({
                    source:sourceDraw,
                    type: _this.mapSelectType
                });
                draw.on("drawend",(e) => {
                  map.removeInteraction(draw);
                });
                map.addInteraction(draw);

                snap = new Snap({source: sourceDraw});
                map.addInteraction(snap);
            }
        };
        var reDraw = document.getElementById('reDraw');
        reDraw.onclick = (e) => {
          map.removeInteraction(snap);
          layers.map(v => {
            if(v.values_.id == "drawLayer"){
              v.getSource().clear()
            }
          });

          addInteraction();
        }


        addInteraction();
        //向地图中添加点击处理程序以呈现弹出式窗口。
        map.on('click',function (evt) {
            var coordinate = evt.coordinate;
            var hdms = toStringHDMS(coordinate);
            // var dfs = _this.coordinateToNumber(hdms);
            content.innerHTML = '<ul>'+'<li>'+"坐标："+'<span>'+'<code>'+hdms+'</code>'+'</span>'+'</li>'+'</ul>';
            let coordinateHtml = [coordinate[0]+0.001,coordinate[1]+0.001]
            overlay.setPosition(coordinateHtml);
        });



    },
    methods: {
      saveCoordinate() {
        let jwdMapArrOld = this.map.getLayers().array_[1].getSource().getFeatures()[0].geometryChangeKey_.target.getCoordinates();
        if(this.mapSelectType=='LineString'){
          jwdMapArrOld.map(v=>{
            v[0]=Number(v[0].toFixed(8))
            v[1]=Number(v[1].toFixed(8))
          })
        }else if(this.mapSelectType=='Polygon'){
          let temp=jwdMapArrOld[0]
          for(let i =0;i<temp.length;i++){
            temp[i][0]=Number(temp[i][0].toFixed(8))
            temp[i][1]=Number(temp[i][1].toFixed(8))
          }
          jwdMapArrOld=temp
        }else{
            jwdMapArrOld[0]=Number(jwdMapArrOld[0].toFixed(8))
            jwdMapArrOld[1]=Number(jwdMapArrOld[1].toFixed(8))
        }

        this.jwdMapArr=jwdMapArrOld
        this.$emit('mapArr',this.jwdMapArr);

        // this.map.removeInteraction(draw);
        // this.map.removeInteraction(snap);
        this.map.getLayers().array_.map(v => {
            if(v.values_.id == "drawLayer"){
              v.getSource().clear()
            }
          });
      }
    },
    components: {}
  };
</script>


<style scoped lang="less">
#map{
  width: 600px;
  height: 400px;
}
.mapBtn {
    text-align: center;
    margin-top: 8px;
    width: 70px;
    height: 25px;
    padding: 0px;
}
</style>
